package com.filetransfer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("/api")
public class FileController {

    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    private final String uploadDir = System.getProperty("user.home") + "/Downloads/FileTransfer/";

    // 存储文件的内存缓存
    private static final ConcurrentHashMap<String, FileInfo> fileStorage = new ConcurrentHashMap<>();

    public FileController() {
        new File(uploadDir).mkdirs();
    }

    @PostMapping("/upload")
    public ResponseEntity<?> uploadFiles(@RequestParam("files") MultipartFile[] files,
            @RequestParam("deviceId") String deviceId) {
        try {
            logger.info("收到文件上传请求，设备ID: {}, 文件数量: {}", deviceId, files.length);

            for (MultipartFile file : files) {
                String fileId = generateFileId();
                logger.info("处理文件: {}, 大小: {} bytes", file.getOriginalFilename(), file.getSize());

                FileInfo fileInfo = new FileInfo(
                        fileId,
                        file.getOriginalFilename(),
                        file.getSize(),
                        deviceId,
                        file.getBytes());

                fileStorage.put(fileId, fileInfo);
                logger.info("文件已存储到内存，fileId: {}", fileId);

                Map<String, Object> message = new HashMap<>();
                message.put("type", "NEW_FILE");
                message.put("fileId", fileId);
                message.put("fileName", file.getOriginalFilename());
                message.put("fileSize", file.getSize());
                message.put("deviceId", deviceId);

                logger.info("准备通过WebSocket广播消息: {}", message);
                messagingTemplate.convertAndSend("/topic/files", message);
                logger.info("WebSocket消息已发送");
            }

            return ResponseEntity.ok().build();
        } catch (Exception e) {
            logger.error("文件上传失败", e);
            return ResponseEntity.badRequest().body("文件上传失败: " + e.getMessage());
        }
    }

    @GetMapping("/download/{fileId}")
    public ResponseEntity<?> downloadFile(@PathVariable String fileId) {
        logger.info("收到文件下载请求，fileId: {}", fileId);

        FileInfo fileInfo = fileStorage.get(fileId);
        if (fileInfo == null) {
            logger.warn("文件未找到，fileId: {}", fileId);
            return ResponseEntity.notFound().build();
        }

        logger.info("文件找到，准备下载: {}", fileInfo.fileName);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileInfo.fileName + "\"")
                .body(fileInfo.fileData);
    }

    private String generateFileId() {
        return java.util.UUID.randomUUID().toString();
    }

    private static class FileInfo {
        String fileId;
        String fileName;
        long fileSize;
        String deviceId;
        byte[] fileData;

        FileInfo(String fileId, String fileName, long fileSize, String deviceId, byte[] fileData) {
            this.fileId = fileId;
            this.fileName = fileName;
            this.fileSize = fileSize;
            this.deviceId = deviceId;
            this.fileData = fileData;
        }
    }
}